<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="400px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="班级" prop="classId">
        <el-input :value="classInfo?.className" disabled placeholder="当前班级" />
      </el-form-item>
      <el-form-item label="是否更新已存在">
        <el-radio-group v-model="updateSupport">
          <el-radio :label="0">不更新</el-radio>
          <el-radio :label="1">更新</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="导入文件" prop="file">
        <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :action="importUrl"
          :auto-upload="false"
          :data="uploadData"
          :headers="uploadHeaders"
          :file-list="fileList"
          :on-success="submitFormSuccess"
          :on-error="submitFormError"
          drag
        >
          <Icon icon="ep:upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <div class="el-upload__tip">
                <el-link @click="importTemplate" type="primary">下载模板</el-link>
              </div>
              <div style="color: #999">仅允许导入xls、xlsx格式文件。</div>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ExamClassStudentApi } from '@/api/system/examclassstudent'
import { ExamClassVO } from '@/api/system/examclass'
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'

defineOptions({ name: 'StudentImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('学生导入') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/system/exam-class-student/import'
const uploadHeaders = ref() // 上传 Header 头
const uploadData = ref() // 上传的额外数据
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的学生数据
const classInfo = ref<ExamClassVO>() // 当前班级信息

const formData = ref({
  classId: undefined
})
const formRules = reactive({
  file: [{ required: true, message: '上传文件不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = (classData: ExamClassVO) => {
  dialogVisible.value = true
  classInfo.value = classData
  updateSupport.value = 0
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  if (!classInfo.value?.id) {
    message.error('请选择班级')
    return
  }
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  uploadData.value = {
    classId: classInfo.value.id,
    updateSupport: updateSupport.value
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = '上传成功数量：' + data.createStudentNames.length + ';'
  for (let i = 0; i < data.createStudentNames.length; i++) {
    text += '< ' + data.createStudentNames[i] + ' >'
  }
  text += '\n更新成功数量：' + data.updateStudentNames.length + ';'
  for (let i = 0; i < data.updateStudentNames.length; i++) {
    text += '< ' + data.updateStudentNames[i] + ' >'
  }
  text += '\n更新失败数量：' + Object.keys(data.failureStudentNames).length + ';'
  for (const key in data.failureStudentNames) {
    text += '< ' + key + ': ' + data.failureStudentNames[key] + ' >'
  }
  message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 文件上传失败 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    classId: undefined
  }
  formRef.value?.resetFields()
}

/** 下载模板 */
const importTemplate = async () => {
  const res = await ExamClassStudentApi.importTemplate()
  download.excel(res, '班级学生导入模板.xls')
}
</script>